var app = getApp();
const apiHost = require('../../../common/api_host.js');
var utils = require('../../../utils/utils.js');
var httpJson=require('../../../utils/http_json.js');

Page({
  getList:function(list,noUserRoom){
    var  url=`${apiHost.config.portalApiHost}/portal/aboveroom/${list}`;
    httpJson.get(url,{},res=>{
      if(res.data.errorCode==0){
       
        // 第一次进来
        // if(noUserRoom==1){
        //   this.setData({
        //     rooms:res.data.body.slice(0,3)
        //   })
        //     let str="";

        //   //随机选择之后三个房间全部塞进去
        //   res.data.body.slice(0,3).forEach((ele)=>{
        //     str+=ele.id+','
        //   })
        //   str=str.substr(0,str.length-1)
        //   this.updateRoom(str)
        // }
        // else{
         
          // if(this.data.roomArr)
          console.log(this.data.roomArr)
          if(this.data.roomArr){
              this.data.roomArr.forEach((ele2)=>{
                ele2=parseInt(ele2)
              })
              res.data.body.forEach((ele)=>{
                this.data.roomArr.forEach((ele2)=>{
                  if(ele.id==ele2){
                    ele.canGo=true
                  }
                })
                // if( this.data.roomArr.indexOf(ele.id)!=-1){
                //   console.log("keyi")
                // }

              })
          }
        
          this.setData({
            rooms:res.data.body
          })
        // }
        wx.hideLoading()
      }
    })
  },
  updateRoom:function(roomIds){
    var  url=`${apiHost.config.portalApiHost}/portal/user/updateRoom`;
    let data={
      roomIds
    }
    httpJson.post(url,data,res=>{
      if(res.data.errorCode==0){
        this.setData({
          'userMsg.roomIds':res.data.body.roomIds
        })
      }})
  },
  getrandomList:function(){
    if(!this.data.randomlist){
      var  url=`${apiHost.config.portalApiHost}/portal/aboveroom/list`;
      httpJson.get(url,{},res=>{
        if(res.data.errorCode==0){
          let randomlist=res.data.body;
          let i = randomlist.length;
          while (i) {
              let j = Math.floor(Math.random() * i--);
              [randomlist[j], randomlist[i]] = [randomlist[i], randomlist[j]];
          }
         if(!this.data.roomArr&&this.data.userMsg.roomIds){
            randomlist.forEach((ele)=>{
             if(this.data.userMsg.roomIds==ele.id){
              ele.showT=true
             }
            
  
            })
         }
          if(this.data.roomArr){
            this.data.roomArr.forEach((ele2)=>{
              ele2=parseInt(ele2)
            })
            randomlist.forEach((ele)=>{
              this.data.roomArr.forEach((ele2)=>{
                if(ele.id==ele2){
                  ele.showT=true
                }
              })
             
  
            })
          }
          this.setData({
            randomlist
          })
        }
      })
    }else{
      let randomlist=this.data.randomlist;
          let i = randomlist.length;
          while (i) {
              let j = Math.floor(Math.random() * i--);
              [randomlist[j], randomlist[i]] = [randomlist[i], randomlist[j]];
          }
          //如果用户进入过的房间是一个
         if(!this.data.roomArr&&this.data.userMsg.roomIds){
            randomlist.forEach((ele)=>{
              ele.showT=false
             if(this.data.userMsg.roomIds==ele.id){
              ele.showT=true
             }
            
  
            })
         }
         //如果大于等于2个
          if(this.data.roomArr){
            this.data.roomArr.forEach((ele2)=>{
              ele2=parseInt(ele2)
            })
            randomlist.forEach((ele)=>{
              ele.showT=false
              this.data.roomArr.forEach((ele2)=>{
                if(ele.id==ele2){
                  ele.showT=true
                }
              })
             
  
            })
          }
          this.setData({
            randomlist
          })

    }
   

  },
  getuserroom:function(){
    var num=0
    var roomids=this.data.userMsg.roomIds
    //只要房间少于三个就显示所有的房间
    if(roomids==null){
      this.getrandomList('list');
      return;
    }
    if(roomids!=null&&roomids.indexOf(',')==-1){
      this.getrandomList('list');
      return;
    }
    if(roomids!=null&&roomids.indexOf(',')!=-1){
      var roomArr =roomids.split(",");
      if(roomArr.length<3){
        this.getrandomList('list');
        return;
      }
    }
    // var  url=`${apiHost.config.portalApiHost}/portal/aboveroom/userRoomlist`;
    // httpJson.get(url,{},res=>{
    //   if(res.data.errorCode==0){
      
      
    //     this.setData({
    //       rooms:res.data.body
    //     })
    //   }
    // })
  },
//  第一次进来的时候选择
  choose:function(e){
    let myid=app.E(e,"myid")
   
    //随机选择
    if(myid==1){
      //第一次
      this.getrandomList()
     
      
      this.setData({
        mychoose:true
      })
    }
    //自己选择
    else if(myid==2){
     this.getList('list')
      this.setData({
        mychoose:false
      })
    }
    ////debuggerger
    
    this.setData({
      first:false,
      upgrade:false,

      canScroll:true
    })
   

  },
  upOrDown:function(e){
    if(e.currentTarget.dataset.myid==1){
      this.setData({
        chooseUnder:false
      })
      
    }else if(e.currentTarget.dataset.myid==2){
      this.setData({
        chooseUnder:true
      })
     
    }


  },
  /**点击了右上角的切换选择方式 */
  change_choose:function(){
/**change_pill为true的时候表示点击了切换选择 
 * change_pill:true正在改变灰色不可按
 * change_pill:false可以点击*/
    if(this.data.change_pill){
      return;
    }    
    //点击了自己选择
    if(this.data.mychoose){
      this.getList('list')
    }
    //随机选择
    if(!this.data.mychoose){
      
       this.getrandomList()
    }
    this.setData({
      mychoose:!this.data.mychoose,
      change_pill:true
    })
    
    setTimeout(()=>{

      this.setData({
      
        change_pill:false
      })
    },300)
  },
  toDetail:function(e){
   
  
  //用户等级进入判断~~！！！
    let roomid=app.E(e,'myid');
    roomid=String(roomid)
    //使得指定哪一个显示文字
    let idx=app.E(e,'idx')
    if(this.data.mychoose){
      // debugger
      this.data.randomlist[idx]['showT']=true
      this.setData({
        randomlist: this.data.randomlist
      })
    }
    
      // 新人
    if(this.data.userMsg.roomIds==null){
      ////debuggerger
      var roomIds=roomid
    }
      //只有一个房间
    if(this.data.userMsg.roomIds!=null&&this.data.userMsg.roomIds.indexOf(',')==-1){
      
        ////debuggerger
        //需要弄个全等
        if(parseInt(this.data.userMsg.roomIds)==parseInt(roomid)){
          var roomIds=-1
        }
        else{
          var  roomIds=this.data.userMsg.roomIds+','+roomid
        }
        
    }
      // 两个房间以上
      if(this.data.userMsg.roomIds!=null&&this.data.userMsg.roomIds.indexOf(',')!=-1){
          ////debuggerger
          var roomArr = this.data.userMsg.roomIds.split(",");
          ////debuggerger
          //  roomIds=this.data.userMsg.roomIds+','+roomid
          if(this.data.userMsg.grade<4){
            ////debuggerger
           
            if(roomArr.indexOf(roomid)==-1){
              ////debuggerger
              if(roomArr.length>=3){
                ////debuggerger
                this.setData({
                  showtip:true
                })
                return;
              }else{
                ////debuggerger
                var  roomIds=this.data.userMsg.roomIds+','+roomid
              }
            }
            else{
              ////debuggerger
              var roomIds=-1
            }
            
          }
          if(this.data.userMsg.grade==4){
            ////debuggerger
            // let choosedRooms=roomArr.slice(0,4);
            if(roomArr.indexOf(roomid)==-1){
              ////debuggerger
              if(roomArr.length>=4){
                ////debuggerger
                this.setData({
                  showtip:true
                })
              return;
              }else{
                ////debuggerger
                var roomIds=this.data.userMsg.roomIds+','+roomid
              }
            } else{
              ////debuggerger
              var roomIds=-1
            }
            
          }
          if(this.data.userMsg.grade==5){
            ////debuggerger
           
            if(roomArr.indexOf(roomid)==-1){
              ////debuggerger
              if(roomArr.length>=5){
                ////debuggerger
                this.setData({
                  showtip:true
                })
              return;
              }else{
              var  roomIds=this.data.userMsg.roomIds+','+roomid
              }
            } else{
              var roomIds=-1
            }
          }
      }

   //当进入同一个房间的时候不发请求
   console.log('roomids!~!~',roomIds)
     if(roomIds==-1){
       if(this.data.mychoose){
         utils.successToast('抽选成功',500)
         setTimeout(()=>{
           wx.navigateTo({
            url: '../room/index/index?id='+e.currentTarget.dataset.myid+"&name="+e.currentTarget.dataset.myname
          })
         },500)
       }else{
         wx.navigateTo({
          url: '../room/index/index?id='+e.currentTarget.dataset.myid+"&name="+e.currentTarget.dataset.myname
        })
       }
       return
      

     }
    //  else{
        var  url=`${apiHost.config.portalApiHost}/portal/user/updateRoom`;
        let data={
          roomIds
        }
        httpJson.post(url,data,res=>{
          ////debuggerger
          if(res.data.errorCode==0){
            ////debuggerger
            this.data.userMsg.roomIds=res.data.body.roomIds
            this.setData({
              userMsg:this.data.userMsg
            })
            ////debuggerger
            //如果是随机选择就等待一会在进入，为了显示房间名称
            if(this.data.mychoose){
              setTimeout(()=>{
                wx.navigateTo({
                  url: '../room/index/index?id='+e.currentTarget.dataset.myid+"&name="+e.currentTarget.dataset.myname
                })
              },500)
              //如果不是随机选择就正常进入
            }else{
              wx.navigateTo({
                url: '../room/index/index?id='+e.currentTarget.dataset.myid+"&name="+e.currentTarget.dataset.myname
              })
            }
          }
        })
    //  }
  },
  // 升级攻略
  tipDetail:function(){
    this.setData({
      tipDetail:true
    })
  },
  // 升级攻略
  noshowtip:function(){
    this.setData({
      showtip:false
     })
  },
  myclose:function(){
    console.log('ee')
    this.setData({
      
      showtip:false,
      tipDetail:false
     
     })
  },
  under_toDetail:function(e){
    let grade=this.data.userMsg.grade
    if(grade==1){
      this.setData({
        showtip:true
      })
      //start1揭开注释
      return;
      //end1
    }
    if(e.currentTarget.dataset.myid==1){
      wx.navigateTo({url:"../underground/brain_hole/today/today"})
    }
    if(e.currentTarget.dataset.myid==2){
      if(grade==2){
        this.setData({
          showtip:true
        })
        //start2解开注释
        return;
        //end2
      }
      wx.navigateTo({url:"../underground/discuss/index/index"})
    }
    // if(e.currentTarget.dataset.id=="院内图书馆"){
    //   if(grade==2){
    //     this.setData({
    //       showtip:true
    //     })
    //     return;
    //   }
    //   wx.navigateTo({url:"../underground/brain_hole/today/today"})
    // }
   

  },
  toSign:function(){
    var  url1=`${apiHost.config.portalApiHost}/portal/usersignup/totalDays`;
    httpJson.get(url1,{},res=>{
      if(res.data.errorCode==0){
        this.setData({
          totalDays:res.data.body,
        })
      }
    })
   
   
    this.setData({
      signMask:true
    })
    

  },
  close:function(){
    this.setData({
      signMask:false
    })
  },
  dayClick:function(event){
    let c_year=event.detail.year;
    let c_month=event.detail.month;
    let c_day=event.detail.day;
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    var buQianDays=[];
    var params={month:'current',color:'#fff',background:"#9E2C2A"};
    // if(c_year==year){
      if(c_month==month){
        params.month='current'
      }
      if(c_month<month||c_year<year){
        params.month='prev'
      }
      params.day=c_day;

      buQianDays.push(params)
     
      this.data.chooseDay.concat(buQianDays)
      this.setData({
        chooseDay:this.data.chooseDay
      })
      console.log(event.detail)

  },
  // 为了立即产生效果
  todaySign:function(){
    if(this.data.todaySign){
      utils.errToast('今日已签~',1000)
    }
    let date = new Date();
    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let day = date.getDate()
    console.log(year,month,day);
    let obj={month:'current',color:'#fff',background:"#9E2C2A"};
    obj.day=day;
    var  url=`${apiHost.config.portalApiHost}/portal/usersignup`;
    httpJson.post(url,{},res=>{
      if(res.data.errorCode==0){
        if(res.data.body.upGrade){
          wx.setStorageSync("upGrade",true)
        }
        utils.successToast('签到成功，经验值加'+res.data.body,1000)
        this.data.chooseDay.push(obj)
        this.data.totalDays++
        this.setData({
          chooseDay:this.data.chooseDay,
          todaySign:true,
          totalDays:this.data.totalDays
        })
      }
    })
  },
  buQian:function(){
    let obj={month:'current',color:'#fff',background:"#ccc"};
    //当还未补签时
    if(!this.data.buQain){
      obj.day=this.data.date_today-1
      this.data.chooseDay.push(obj)
      this.setData({
        chooseDay:this.data.chooseDay,
        buQain:true,
  
      })
    }
    else{
      this.data.chooseDay.pop(obj)
      this.setData({
        buQain:!this.data.buQain,
        chooseDay:this.data.chooseDay
      })
    }
    
   
  },
  getSignList:function(){
    var  url=`${apiHost.config.portalApiHost}/portal/usersignup/list`;
    httpJson.get(url,{},res=>{
      if(res.data.errorCode==0){
        this.setData({
          status:res.data.body.status,
        })
       
        var signList=res.data.body.signList;
         if(signList.length==0){
            return;
         }
        // 当前的时间
        let date_now = new Date();
        let year_now = date_now.getFullYear()
        let month_now = date_now.getMonth() + 1
        let day_now = date_now.getDate()
        signList.forEach((ele)=>{
        // 1.把已签到的日期的数据存起来,未来显示已签到过的日期
          // 后台拿到的数据
          let date = new Date(ele.createTime);
          let year = date.getFullYear()
          let month = date.getMonth() + 1
          let day = date.getDate();
          console.log('签到列表',year,month,day)
          var obj={color:'#fff',background:"#9E2C2A",day:day};
          if(month==month_now){
            obj.month='current'
            if(day==day_now){
              obj.background='#9E2C2A'
            }
          }
          else{
            obj.month='prev'
          }
          this.data.chooseDay.push(obj)
        })

        this.setData({
          chooseDay:this.data.chooseDay
        })
        // 判断上一天是否签到
          // var oneDay=86400000;
         
     //拿到最后一天签到的日期，列表最后一个可能是今天也可能是昨天
        //start1.测试所用，测试补签
          // var date_today=new Date().getDate();
          //   this.setData({
          //     canBuQian:true,
          //     date_today
          //   })
        //end1
          if(signList.length<2){
            return;
        }
        var signList0=new Date( signList[0].createTime).getDate();
        var signList1=new Date( signList[1].createTime).getDate();
        var x=utils.formatDate2(new Date( signList[0].createTime))
    
      //拿到今天的日期
        var date_today=new Date().getDate();
       
        //如果今天签到了就对比上一天，如果今天没签到就对比今天(只能补签这个月，只能补签前一天，所有不用判断1号减1的情况)
        if(
          (date_today!=1&&signList0!=date_today&& signList0!=date_today-1)
          ||
          (date_today!=1&&signList0==date_today&&signList1!=date_today-1)
        ){
       
            this.setData({
               canBuQian:true,
               date_today
            })
         
        }
      

        
      
        
      }
    })
  },
  /**能够补签之后才可能触发这个函数 */
  buQianBtn:function(){
    var _this=this;
  // debuggerger
    wx.showModal({
      title: '确认补签？',
      content: '补签将消耗两点碎片哦?',
      success(res) {
        if(res.confirm){
          let time=new Date();

          //debuggerger
          let BuQianTime=time.getFullYear() + "-" +  time.getMonth() + 1  + "-" + (time.getDate() -1);
          // console.log(time.getFullYear() + "-" +  time.getMonth() + 1 + "-" + (time.getDate() - 1))
          BuQianTime=String(BuQianTime)
        
          var  url=`${apiHost.config.portalApiHost}/portal/usersignup/signDay`;
          let data={
            signDay:BuQianTime
          }
          httpJson.post(url,data,res=>{
            if(res.data.errorCode==0){

              utils.successToast("补签成功",500)
              let obj={month:'current',color:'#fff',background:"#9E2C2A"};
              obj.day=_this.data.date_today-1
              _this.data.chooseDay.push(obj)
              _this.setData({
                //补签成功后
                buQianWan:true,
                //日历的变化
                chooseDay:_this.data.chooseDay,
                buQain:false
              })

            }
            if(res.data.errorCode==1){
              utils.errToast('经验值不足',500)
            }
          })
        
        }
      }
    })
  },
  getuser:function(){
    var  url=`${apiHost.config.portalApiHost}/portal/user/update`;
   
    httpJson.post(url,{},res=>{
      if(res.data.errorCode==0){
        let userMsg=res.data.body;
          //这个时候可以进入所有房间
        if(userMsg.roomIds==null){
          this.setData({
            canGoAll:true
          })
        }
          //这个时候可以进入所有房间
        if(userMsg.roomIds!=null&&userMsg.roomIds.indexOf(',')==-1){
          this.setData({
            canGoAll:true
          })
        }
        //为了显示哪些药丸是亮色的
        if(userMsg.roomIds!=null&&userMsg.roomIds.indexOf(',')!=-1){
          ////debuggerger
          var roomArr = userMsg.roomIds.split(",");
          if(roomArr.length>=3){
            roomArr.forEach((ele)=>{
              ele=parseInt(ele)
              console.log(typeof ele)
            })
            this.setData({
              roomArr
            })
          }else{
            //这个时候可以进入所有房间
            this.setData({
              canGoAll:true
            })
          }
        }
        // 判断他是否是第一次进来
        if(res.data.body.roomIds==null&&this.data.fromReg!=1){
          // ////debuggerger
          this.setData({
            first:true
          })
          wx.reLaunch({url:"/pages/register/register"})
         
        }
        else if(res.data.body.roomIds!=null){
          // ////debuggerger
          this.setData({
            first:false
          })
        }
        this.setData({
          userMsg:res.data.body
        })
        this.data.mychoose?this.getrandomList(): this.getList("list")
       
      }
    })
  },
  getRoomArr:function(){
    var  url=`${apiHost.config.portalApiHost}/portal/user/update`;
   
    httpJson.post(url,{},res=>{
      if(res.data.errorCode==0){

      }})
  },

  formSubmit: function(e) {


    var formId = e.detail.formId;
  
    let path = `${apiHost.config.portalApiHost}/portal/userformId/add`;
    httpJson.post(path, { 'formId': formId}, function (data) {
      let res = data.data;
     
    })
   
  },
  /**
   * 页面的初始数据
   */
  data: {
    // upgrade:true,
    // 档案等级
    showtip:false,

    next:false,
    prev:false,
    buQain:false,
    pillImg:'../../../images/index/1L/pill.png',
    pill2Img:'../../../images/index/1L/pill2.png',
    chooseDay:[],
    signedDay:0,
    rooms:[
    ],
  
    under_item1:{
      id:1,title:"脑洞24H",tip:"<每日更新限时参与>"
    },
    under_item2:{
      id:2,title:"衍生同人",tip:"<惊人院就在你的身边>"
    },

    minipro:{title:"惊人阅读",tip:"<去看惊人院的故事>"},
    /**正常一进来 */
    canScroll:true,
    /**true是自己选择，false是随机选择 */
    mychoose:false,
    /**为了测试等会记得改成false */
    chooseUnder:false,
    //正常时false
    signMask:false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  getUpGrade:function(){
    try {
      const value = wx.getStorageSync('upGrade')
      if (value) {
       this.setData({
        upgrade:true,
//为了判断当前的等级
       upgrade2:true
       })
       wx.removeStorageSync('upGrade')
       setTimeout(()=>{
          this.setData({
            upgrade:false
          })
       },2000)
      }
    } catch (e) {
      // Do something when catch error
    }
    

  },
  onLoad: function (options) {
    
    app.verifyLogin(()=>{
      this.getUpGrade()
      
     
     
      this.getSignList()
    })
    
    wx.showLoading({
      title: '加载中',
    })
   
    console.log(options)
    
    if(options.msg=='reg'){
      ////debuggerger
      wx.hideLoading()

      this.setData({
        fromReg:1,

        first:true,
        canScroll:false
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log("ready")

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getuser();
   

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(res) {
    app.share()
    if (res.from === 'button') {
      var content=res.target.dataset.content
     
      if(content.length>50){
        content=content.substr(0,50)+'...'
      }
      var title=content
    }
    if(res.from === 'menu'){
      var imageUrl="/images/index/reply/reply.png";
      var title='我正在惊人院，邀请你来……'
    }
    return {
      title,
      imageUrl
      
    }
  }
})